<h2><?php echo $form_title ?></h2>

<div id="form-elements">
  <div class="form-element-thumb form-text" type="text"></div>
  <div class="form-element-thumb form-select" type="select"></div>
</div>

<div id="form-body"></div>

<script>
$(document).ready(function() {

  <?php foreach ($elements as $element) { ?>
  var url = '<?php echo $response->makeUrl('/admin/form_builder/elements', 
    array('action' => 'edit', 'form_id' => $form_id, 'element_id' => $element['element_id'])) ?>';
  var element = $('<div>').load(url);
  $('#form-body').append(element);
  <?php } ?>

  $('#the-form').submit(function() {
    $(this).find('[type=hidden]').remove();

    $('#form-body .form-element').each(function(index, value) {
      $('#the-form').append(
        $('<input>')
          .attr('type', 'hidden')
          .attr('name', 'element-' + index)
          .val($(this).find(':input').serialize())
      );
    });
  });

  $('#form-body').sortable({
    placeholder: "form-element",

    stop: function(event, ui) {
      if ($(ui.item).hasClass('form-element-thumb')) {
        //var element = ui.item.find('.form-element').clone().show();

        var type = $(ui.item).attr('type');
        var url = '<?php echo $response->makeUrl('/admin/form_builder/elements', array('action' => 'create', 'form_id' => $form_id)) ?>';
        var element = $('<div>').load(url, { element_type:type });

        $(this).append(element);

        $(ui.item).remove();
      }
    }
  });

  $('.form-element-thumb').draggable({
    connectToSortable:'#form-body',

    helper:function(event) {
      var element = $(event.target);
      var helper = element.clone();//.find('.form-element').clone().show();

      return helper;
    }
  });
});
</script>

<style>
#form-elements {
  border:1px solid #ccc;
  padding:10px;
  margin-bottom:10px;
}

#form-elements .form-element-thumb {
  display:inline-block;
}

#form-body {
  border:1px solid #ccc;
  padding:10px;
}

.form-element {
  background:#ccc;
  padding:10px;
  margin-bottom:10px;
}

.form-element-thumb {
  width:30px;
  height:30px;
  margin-right:5px;
  background:#ccc;
}
</style>